# coding:utf-8
"""
description:找到最新测试报告附件并发送邮件
"""
import configparser
import os, smtplib, os.path
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from common.Log import logger, LOG

from config.GlobalParameter import CONFIG_DIR, report_path, LOG_DIR, record_path


class send_email:
    """读取config下的ini文件"""
    conData = configparser.ConfigParser()
    conData.read(CONFIG_DIR, encoding='utf-8')
    FromName = conData.get("EmailUser", "email_name")
    server = conData.get("EmailUser", "smtp_sever")
    Pwd = conData.get("EmailUser", "email_password")
    ToName = conData.get("EmailUser", "email_To")
    SUBJECT = conData.get("EmailUser", "SUBJECT")
    text = conData.get("EmailUser", "text")

    # 定义邮件内容
    @logger("定义邮件内容……")
    def email_init(self, *data):
        # with open(report, 'rb') as f:
        #     mail_body = f.read()

        # 创建一个带附件的邮件实例
        msg = MIMEMultipart()
        # msg.attach(MIMEText(mail_body,'html','utf-8')) # 以测试报告附件作为邮件正文
        msg.attach(MIMEText(self.text, 'html', 'utf-8'))

        for i in range(len(data)):  # 循环把测试报告，record文件和数据log作为附件
            file = MIMEText(open(data[i][0], 'rb').read(), 'html', 'utf-8')
            file["Content-Disposition"] = 'attachment;filename=' + data[i][1]
            msg.attach(file)  # 添加测试报告附件

        msg['Subject'] = self.SUBJECT  # 邮件标题
        msg['From'] = self.FromName  # 发件人
        msg['To'] = self.ToName  # 收件人列表
        try:
            server = smtplib.SMTP(self.server)
            server.login(self.FromName, self.Pwd)
            server.sendmail(msg['From'], msg['To'].split(';'), msg.as_string())
            server.quit()
        except smtplib.SMTPException:
            LOG.error(u'邮件发送测试报告失败:' + __file__)

    def Attachment(self, path):
        """
        找到最新文件,返回最新文件路径和文件名
        :param path:
        :return:
        """
        # 找到最新的测试报告
        Attach_list = os.listdir(path)  # 拿目录下所有文件
        Attach_list.sort(key=lambda fn: os.path.getmtime(path + '\\' + fn) if not os.path.isdir(
            path + '\\' + fn) else 0)  # 进行时间小到大排序
        new_report = os.path.join(path, Attach_list[-1])  # 取最新日期文件的路径
        print(new_report)
        return new_report, Attach_list[-1]  # 不会进入这步

    @logger("发送邮件……")
    def sendReport(self):
        # 发送邮件
        self.email_init(self.Attachment(report_path), self.Attachment(LOG_DIR), (record_path, "UnautomatedRecord.txt"))
